package com.leige.testocrdemo

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.leige.tesseractocrlibrary.TesseractInitHelper
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream


/**
 * Created by liulei
 * 2019/12/21 18:20
 * {描述这个类功能}
 */
class TestOcrActivity : AppCompatActivity() {


    private val reqPermissionReadFile = 1001
    private val WRITE_EXTERNAL_STORAGE = android.Manifest.permission.WRITE_EXTERNAL_STORAGE

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_ocr)

        val ret = ActivityCompat.checkSelfPermission(
            this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                , reqPermissionReadFile
            )
        } else {
            processImgInBackground()
        }

    }

    private val tesseractInitHelper = TesseractInitHelper()

    private fun processImgInBackground() {
        GlobalScope.launch {
            Log.e("tag", "init TesseractOCR at background thread.")

            tesseractInitHelper.initConfig(
                setConfig = TesseractInitHelper.Config(
                    "/storage/emulated/0/Download/chi_sim.traineddata",
                    "chi_sim.traineddata",
                    "chi_sim"
                )
            )
            tesseractInitHelper.init(this@TestOcrActivity)

            delay(1000L)

            var bitmap: Bitmap? = null
            val file = File("/storage/emulated/0/Download/testOpencv/idCard_1576910908057.jpg")
            try {
                //testOpencv
                val fd = FileInputStream(file).fd
                val opts = BitmapFactory.Options()
                bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts)
            } catch (ex: Throwable) {
                ex.printStackTrace()
            }

            if (bitmap != null) {
                Log.e("ocr", "ocr process ${file.path} before")
                val ocrResult = tesseractInitHelper.getOCRResult(bitmap)
                Log.e("ocr", "get ocrResult = $ocrResult")
            }

        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == reqPermissionReadFile) {
            for ((i, permiss) in permissions.withIndex()) {
                if (permiss == WRITE_EXTERNAL_STORAGE && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    onWriteSdPermissionObtained()
                    break
                }
            }
        }
    }

    private fun onWriteSdPermissionObtained() {
        processImgInBackground()
    }

    override fun onDestroy() {
        super.onDestroy()
        tesseractInitHelper.release()
    }

}